//
//  MyDocument.m
//  This file is part of D&D Manager
//
//  Created by Matthew Hutton on 30/09/2006.
//  Copyright Matthew Hutton 2006-2007.
//
//D&D Manager, a D&D Character and battle management program.
//Copyright (C) 2007, Matthew Hutton
//
//This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License along with this program; if not, write to:
//The Free Software Foundation, Inc.,
//51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

#import "MyDocument.h"
@implementation MyDocument

- (id)init 
{
    self = [super init];
    if (self != nil) {
		licenceShowedThisSession=NO;
        // initialization code
		origObjectsCopied=[[NSMutableArray alloc] initWithCapacity:1];
		newObjectsCopied=[[NSMutableArray alloc] initWithCapacity:1];
		windowShown=NO;
    }
    return self;
}
/*- (void)makeWindowControllers{
	[self addWindowController:[[NSWindowController alloc] initWithWindowNibName:@"MyDocument"]];
}*/
-(void)showWindows{
	if([[[[self appController] battleController] battleScreen] isVisible]){
		//battle display already visible so do nothing.
	}else{
		[super showWindows];
	}
}
- (NSString *)windowNibName 
{
    return @"MyDocument";
}

- (void)windowControllerDidLoadNib:(NSWindowController *)windowController 
{
    [super windowControllerDidLoadNib:windowController];
    // user interface preparation code
}
-(IBAction)importCharactersFromOtherFiles:(id)sender{
	if(allCharacters==nil){
		allCharacters=[[NSMutableArray alloc] initWithCapacity:10];
	}
	if(allSpells==nil){
		allSpells=[[NSMutableArray alloc] initWithCapacity:10];
	}
	if(selectedCharacters==nil){
		selectedCharacters=[[NSMutableArray alloc] initWithCapacity:5];
	}
	if(selectedSpells==nil){
		selectedSpells=[[NSMutableArray alloc] initWithCapacity:5];
	}
	[selectedCharacters removeAllObjects];
	[selectedSpells removeAllObjects];
	[self refreshCharactersAndSpells:nil];
	[NSApp beginSheet:importSheet
	   modalForWindow:mainWindow
		modalDelegate:self
	   didEndSelector:nil
		  contextInfo:NULL];
	//process allFiles and skip this document.
	//MyDocument *myDoc=(MyDocument *)[[NSDocumentController sharedDocumentController] currentDocument];//taken from LaTeXiT.
}
-(IBAction)refreshCharactersAndSpells:(id)sender{
	NSArray *allFiles=[[NSDocumentController sharedDocumentController] documents];
	[allCharacters removeAllObjects];
	[allSpells removeAllObjects];
	int i;
	for(i=0;i<[allFiles count];i++){
		MyDocument *doc=(MyDocument *)[allFiles objectAtIndex:i];
		if([doc isEqualTo:self]){
			//NSLog(@"skipping self");
		}else{
			[allCharacters addObjectsFromArray:[[doc getAllCharacters] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"temp==0"]]];
			[allSpells addObjectsFromArray:[doc getAllSpells]];
		}
	}
	[allCharacters sortUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]]];
	[allSpells sortUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]]];
	[importCharacterTable reloadData];
	[importSpellTable reloadData];
	[importCharacterTable2 reloadData];
	[importSpellTable2 reloadData];
	if([mainTabView indexOfTabViewItem:[mainTabView selectedTabViewItem]]==3){
		[importTabs selectTabViewItemAtIndex:1];
	}else{
		[importTabs selectTabViewItemAtIndex:0];
	}
}
-(NSArray *)getAllCharacters{
	/*NSString *pred=[[characterController filterPredicate] predicateFormat];
	[characterController setFilterPredicate:nil];
	NSArray *array=[characterController arrangedObjects];
	[characterController setFilterPredicate:[NSPredicate predicateWithFormat:pred]];
	return array;*/
	NSManagedObjectContext *mObjC=[self managedObjectContext];
	NSManagedObjectModel *model=[[mObjC persistentStoreCoordinator] managedObjectModel];
		return [mObjC executeFetchRequest:[model fetchRequestFromTemplateWithName:@"character" substitutionVariables:[NSDictionary dictionary]]
									error:nil];
}
-(NSArray *)getAllSpells{
	/*NSString *pred=[[spellController filterPredicate] predicateFormat];
	[spellController setFilterPredicate:nil];
	NSArray *array=[spellController arrangedObjects];
	[spellController setFilterPredicate:[NSPredicate predicateWithFormat:pred]];
	return array;*/
	NSManagedObjectContext *mObjC=[self managedObjectContext];
	NSManagedObjectModel *model=[[mObjC persistentStoreCoordinator] managedObjectModel];
	return [mObjC executeFetchRequest:[model fetchRequestFromTemplateWithName:@"NewSpell" substitutionVariables:[NSDictionary dictionary]]
								error:nil];
}
-(IBAction)addCharactersToImport:(id)sender{
	NSMutableSet *set=[[NSMutableSet alloc] initWithCapacity:10];
	[set addObjectsFromArray:selectedCharacters];
	[set addObjectsFromArray:[allCharacters objectsAtIndexes:[importCharacterTable selectedRowIndexes]]];
	[selectedCharacters removeAllObjects];
	[selectedCharacters addObjectsFromArray:[set allObjects]];
	[selectedCharacters sortUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]]];
	
	[importCharacterTable2 reloadData];
}
-(IBAction)removeCharactersFromImport:(id)sender{
	[selectedCharacters removeObjectsAtIndexes:[importCharacterTable2 selectedRowIndexes]];
	[importCharacterTable2 reloadData];
}
-(IBAction)addSpellsToImport:(id)sender{
	NSMutableSet *set=[[NSMutableSet alloc] initWithCapacity:10];
	[set addObjectsFromArray:selectedSpells];
	[set addObjectsFromArray:[allSpells objectsAtIndexes:[importSpellTable selectedRowIndexes]]];
	[selectedSpells removeAllObjects];
	[selectedSpells addObjectsFromArray:[set allObjects]];
	[selectedSpells sortUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]]];
	[importSpellTable2 reloadData];
}
-(IBAction)removeSpellsFromImport:(id)sender{
	[selectedSpells removeObjectsAtIndexes:[importSpellTable2 selectedRowIndexes]];
	[importSpellTable2 reloadData];
}
-(IBAction)actuallyImporting:(id)sender{
	[importSheet orderOut:self];
	[NSApp endSheet:importSheet];
	[appController characterStuffNeedsSettingUp];
	NSManagedObjectContext *mObjC=[self managedObjectContext];
	int i;
	NSArrayController *characterController=[appController characterController];
	NSLog(@"processing characters");
	for(i=0;i<[selectedCharacters count];i++){
		NSManagedObject *obj=[selectedCharacters objectAtIndex:i];
		NSLog(@"starting duplication");
		NSManagedObject *newObj=[obj newDuplicateWithParent:obj
								   intoManagedObjectContext:mObjC
									   nullifyRelationships:NO
													 spells:NO];
		NSLog(@"ending duplication");
		if(![[newObj managedObjectContext] isEqualTo:mObjC]){
			[mObjC insertObject:newObj];
		}
		if(![newObj validateForUpdate:nil]){
			NSLog(@"newObj is invalid");
		}else{
			//NSLog(@"newObj is valid");
		}
		if(newObj!=nil){
			[characterController addObject:newObj];
		}
	}
	NSLog(@"processing spells");
	for(i=0;i<[selectedSpells count];i++){
		NSManagedObject *spell=[selectedSpells objectAtIndex:i];
		NSManagedObject *newSpell=[spell newDuplicateWithParent:spell
									   intoManagedObjectContext:mObjC
										   nullifyRelationships:NO
														 spells:YES];
		if(![[newSpell managedObjectContext] isEqualTo:mObjC]){
			[mObjC insertObject:newSpell];
		}
		if(![newSpell validateForUpdate:nil]){
			NSLog(@"newSpell is invalid");
		}else{
			//NSLog(@"newObj is valid");
		}
	}
	NSLog(@"finished processing spells");
	//NSLog(@"current document=%@",[[NSDocumentController sharedDocumentController] currentDocument]);
	//to fix dupication bug.
	[characterController setAutomaticallyPreparesContent:NO];
	[characterController prepareContent];
	[characterController setAutomaticallyPreparesContent:YES];
	//end fix.
	[self clearDuplicationArrays];
	[allSpells removeAllObjects];
	[allCharacters removeAllObjects];
	[selectedSpells removeAllObjects];
	[selectedCharacters removeAllObjects];
}
-(IBAction)cancelImport:(id)sender{
	[importSheet orderOut:sender];
	[NSApp endSheet:importSheet];
	[allSpells removeAllObjects];
	[allCharacters removeAllObjects];
	[selectedSpells removeAllObjects];
	[selectedCharacters removeAllObjects];
}
-(void)windowDidBecomeKey:(NSNotification *)aNotification{
	if([[aNotification object] isEqualTo:mainWindow]){
		if(windowShown){
			//now check buttons.
			//[self checkMetadata];
			[appController characterStuffNeedsSettingUp];
		}
	}
}
-(void)windowDidUpdate:(NSNotification *)aNotification{
	if([[aNotification object] isEqualTo:mainWindow] && !windowShown){
		windowShown=YES;
		[(MenuController *)[NSApp delegate] disableAbsolutelyAllButtons];
		if(![[NSUserDefaults standardUserDefaults] boolForKey:@"licenceDisplayed2"] && !licenceShowedThisSession){
			[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"licenceDisplayed"];
			//display software licence.
			//NSLog(@"displaying licence");
			if([[NSUserDefaults standardUserDefaults] objectForKey:@"licenceDisplayed2"]!=nil){
				//NSLog(@"displayed before");
				[alwaysDisplayButton setState:1];
			}else{
				[alwaysDisplayButton setState:0];
			}
			[NSApp beginSheet:softwareLicencePanel
			   modalForWindow:[aNotification object]
				modalDelegate:self
			   didEndSelector:nil
				  contextInfo:NULL];
			licenceShowedThisSession=YES;
		}else{
			[(MenuController *)[NSApp delegate] enableDiceAndLogButtons];
			[appController characterStuffNeedsSettingUp];
		}
	}
}
-(void)windowWillClose:(NSNotification *)aNotification{
	if([[aNotification object] isEqualTo:mainWindow]){
		[(MenuController *)[NSApp delegate] disableAbsolutelyAllButtons];
	}
}
- (void)windowDidResignKey:(NSNotification *)aNotification{
	if([[aNotification object] isEqualTo:mainWindow]){
		//NSLog(@"not key");
		[(MenuController *)[NSApp delegate] disableAllButtons];
	}
}
-(void)canCloseDocumentWithDelegate:(id)delegate shouldCloseSelector:(SEL)shouldCloseSelector contextInfo:(void *)contextInfo{
	if([[NSUserDefaults standardUserDefaults] boolForKey:@"clearLogOnExit"]){
		[appController clearLogSheet:self];
	}
	[super canCloseDocumentWithDelegate:delegate shouldCloseSelector:shouldCloseSelector contextInfo:contextInfo];
}
-(IBAction)licenceAgreed:(id)sender{
	[(MenuController *)[NSApp delegate] enableDiceAndLogButtons];
	[appController characterStuffNeedsSettingUp];
	[softwareLicencePanel orderOut:self];
	[NSApp endSheet:softwareLicencePanel];
	//NSLog(@"state=%d",[alwaysDisplayButton state]);
	if([alwaysDisplayButton state]==1){
		//NSLog(@"setting no");
		[[NSUserDefaults standardUserDefaults] setBool:NO
												forKey:@"licenceDisplayed2"];
	}else{
		//NSLog(@"setting yes");
		[[NSUserDefaults standardUserDefaults] setBool:YES
												forKey:@"licenceDisplayed2"];
	}
	//check metadata.
	[appController characterStuffNeedsSettingUp];
}
-(IBAction)licenceNotAgreed:(id)sender{
	[softwareLicencePanel orderOut:self];
	[NSApp endSheet:softwareLicencePanel];
	[self updateChangeCount:2];
	//NSLog(@"state=%d",[alwaysDisplayButton state]);
	//NSLog(@"setting no");
	[[NSUserDefaults standardUserDefaults] setBool:NO
											forKey:@"licenceDisplayed2"];
	[NSApp terminate:self];
}
-(AppController *)appController{
	return appController;
}
-(int)indexInOrigObjectsOfTheObject:(NSManagedObject *)obj{
	int i;
	BOOL broken=NO;
	for(i=0;i<[origObjectsCopied count];i++){
		if([[origObjectsCopied objectAtIndex:i] isEqualTo:obj]){
			broken=YES;
			break;
		}
	}
	if(broken){
		return i;
	}else{
		return -1;
	}
}
-(NSManagedObject *)origObjectAtIndex:(int)index{
	return [origObjectsCopied objectAtIndex:index];
}
-(NSManagedObject *)newObjectAtIndex:(int)index{
	return [newObjectsCopied objectAtIndex:index];
}
-(void)addOrigObject:(NSManagedObject *)obj{
	if(obj==nil){
		NSLog(@"attempting to add nil as an original object");
		return;
	}
	[origObjectsCopied addObject:obj];
}
-(void)addNewObject:(NSManagedObject *)obj{
	if(obj==nil){
		NSLog(@"attempting to add nil as a new object");
		return;
	}
	[newObjectsCopied addObject:obj];
}
-(void)clearDuplicationArrays{
	[origObjectsCopied removeAllObjects];
	[newObjectsCopied removeAllObjects];
}

-(BOOL)configurePersistentStoreCoordinatorForURL:(NSURL *)url ofType:(NSString *)fileType error:(NSError **)error{
	BOOL ok=[super configurePersistentStoreCoordinatorForURL:url ofType:fileType error:error];
	if(ok){
		NSPersistentStoreCoordinator *psc=[[self managedObjectContext] persistentStoreCoordinator];
		NSArray *stores=[psc persistentStores];
		if([stores count]>0){
			//NSLog(@"saving metadata");
			//NSLog(@"store.count=%d",[stores count]);
			id store=[stores objectAtIndex:0];
			[psc setMetadata:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSNumber numberWithInt:83],[NSNumber numberWithInt:80],@"1.3",nil] forKeys:[NSArray arrayWithObjects:@"fileVersion",@"minSupportedVersion",@"shortMinSupportedVersion",nil]] forPersistentStore:store];
		}		
	}
	return ok;
}
-(int)numberOfRowsInTableView:(NSTableView *)aTableView{
	if([aTableView isEqualTo:importCharacterTable]){
		return [allCharacters count];
	}else if([aTableView isEqualTo:importSpellTable]){
		return [allSpells count];
	}else if([aTableView isEqualTo:importCharacterTable2]){
		return [selectedCharacters count];
	}else if([aTableView isEqualTo:importSpellTable2]){
		return [selectedSpells count];
	}
	return 0;
}
-(id)tableView:(NSTableView *)aTableView
objectValueForTableColumn:(NSTableColumn *)aTableColumn
		   row:(int)row{
	if([aTableView isEqualTo:importCharacterTable]){
		return [[allCharacters objectAtIndex:row] valueForKey:@"name"];
	}else if([aTableView isEqualTo:importSpellTable]){
		return [[allSpells objectAtIndex:row] valueForKey:@"name"];
	}else if([aTableView isEqualTo:importCharacterTable2]){
		return [[selectedCharacters objectAtIndex:row] valueForKey:@"name"];
	}else if([aTableView isEqualTo:importSpellTable2]){
		return [[selectedSpells objectAtIndex:row] valueForKey:@"name"];
	}
	return nil;
}
@end
